package interview.tree;

/**
 * Created with IntelliJ IDEA.
 * Description: 遍历树
 * User: xxm
 * Date: 2018-02-22
 * Time: 13:11
 */
public class TreeTraversal {

    /**
     * 前序
     *
     * @param root
     */
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.getValue() + " ");
        preOrder(root.getLeft());
        preOrder(root.getRight());
    }

    /**
     * 中序
     *
     * @param root
     */
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.getLeft());
        System.out.print(root.getValue() + " ");
        inOrder(root.getRight());
    }

    /**
     * 后序
     *
     * @param root
     */
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.getLeft());
        postOrder(root.getRight());
        System.out.print(root.getValue() + " ");
    }

    public static void main(String[] args) {
        TreeCreator creator = new TreeCreator();
        TreeTraversal traversal = new TreeTraversal();
        TreeNode sampleTree = creator.createSampleTree();

        System.out.print("前序遍历: ");
        traversal.preOrder(sampleTree);
        System.out.println();

        System.out.print("中序遍历: ");
        traversal.inOrder(sampleTree);
        System.out.println();

        System.out.print("后序遍历: ");
        traversal.postOrder(sampleTree);
    }
}
